<template>
  <!-- 操作栏 -->
  <el-row class="mb-10px" justify="end">
    <el-button @click="openForm('create')">
      <Icon class="mr-5px" icon="ep:edit" />
      创建开票记录
    </el-button>
  </el-row>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true">
      <el-table-column type="selection" width="55" />
      <el-table-column label="发票编号" align="center" prop="code" />
      <el-table-column label="开票内容" align="center" prop="content" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="开票金额" align="center" prop="receiptAmount" />
      <el-table-column
        label="开票日期"
        align="center"
        prop="receiptDate"
        :formatter="dateFormatter2"
      />
      <el-table-column label="开票类型" align="center" prop="receiptType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_RECEIPT_TYPE" :value="scope.row.receiptType" />
        </template>
      </el-table-column>
      <el-table-column label="开票状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_RECEIPT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            v-hasPermi="['crm:receipt:query']"
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
          >
            查看
          </el-button>
          <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:receipt:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <!-- <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:receipt:update']"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审批
          </el-button>
          <el-button
            v-else
            link
            v-hasPermi="['crm:receipt:update']"
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button> -->
          <el-button
            v-hasPermi="['crm:receipt:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ReceiptForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ReceiptApi, Receipt } from '@/api/crm/receipt'
import ReceiptForm from './ReceiptForm.vue'
import { TabsPaneContext } from 'element-plus'
import * as CustomerApi from '@/api/crm/customer'

/** crm发票管理 列表 */
defineOptions({ name: 'Receipt' })

const props = defineProps<{
  customerId?: number // 客户编号
  contractId?: number // 合同编号
}>()

const { push } = useRouter()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Receipt[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  customerId: props.customerId,
  customerName: undefined,
  contractId: props.contractId,
  contractCode: undefined,
  receiptAmount: undefined,
  receiptDate: [],
  receiptType: undefined,
  titleId: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  remark: undefined,
  createTime: [],
  ownerUserId: undefined,
  sceneType: '1' // 默认和 activeName 相等
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReceiptApi.getReceiptPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, props.customerId, props.contractId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReceiptApi.deleteReceipt(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除crm发票管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ReceiptApi.deleteReceiptList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Receipt[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ReceiptApi.exportReceipt(queryParams)
    download.excel(data, 'crm发票管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.sceneType = tab.paneName
  handleQuery()
}

/** 提交审核 **/
const handleSubmit = async (row: Receipt) => {
  await message.confirm(`您确定提交【${row.content}】审核吗？`)
  await ReceiptApi.submitReceipt(row.id)
  message.success('提交审核成功！')
  await getList()
}

/** 查看审批 */
const handleProcessDetail = (row: Receipt) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  customerList.value = await CustomerApi.getCustomerSimpleList()
})
</script>
